package com.xsq.consumer.dubboconsumer.filter;

import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName TPMonitor
 * @Description TODO
 * @Author xsq
 * @Date 2020/6/24 14:59
 **/
@Slf4j
public class TPMonitor implements Runnable {
    //一分钟过期
    private static final Integer VALID_TIME = 1000 * 60;
    private Map<Long, Long> map = new ConcurrentHashMap<>(2000);

    /**
     * 记录每次的运行时间
     *
     * @param currentTime
     * @param runTime
     */
    public void record(Long currentTime, Long runTime) {
        map.put(currentTime, runTime);
    }

    /**
     * 去除超过一分钟的无效数据
     */
    public void clearValidTime() {
        Long Oldtime = System.currentTimeMillis() - VALID_TIME;
        Set<Long> times = map.keySet();
        for (Long time : times) {
            if (time < Oldtime) {
                map.remove(time);
            }
        }
    }

    /**
     * 开启线程每5s打印一次TP90和TP99
     */
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(5000);
                clearValidTime();
                if (map.size() == 0) {
                    continue;
                }
                int tp90 = (int) (map.size() * 0.9);
                int tp99 = (int) (map.size() * 0.9);
                Collection<Long> values = map.values();
                //把map的值按从大到小排序,并转换成数组
                Object[] objects = values.stream().sorted().toArray();
                log.info("----------->tp90:{}ms", objects[tp90]);
                log.info("----------->tp99:{}ms", objects[tp99]);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
